<?php
/**
 * @category	Plugins
 * @package		JomSocial
 * @copyright (C) 2008 by Slashes & Dots Sdn Bhd - All rights reserved!
 * @license		GNU/GPL, see LICENSE.php
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

require_once( JPATH_ROOT . DS . 'components' . DS . 'com_community' . DS . 'libraries' . DS . 'core.php');

if(!class_exists('plgCommunityFriendsLocation'))
{
	class plgCommunityFriendsLocation extends CApplications
	{
		var $_user		= null;
		var $name		= "Friend's Location";
		
	    function plgCommunityFriendsLocation(& $subject, $config)
		{
			$this->_user	= CFactory::getRequestUser();
			parent::__construct($subject, $config);
	    }
		
		function getLocationFieldId($town_field_code, $state_field_code, $country_field_code)
		{
			$db =& JFactory::getDBO();
			$sql = "SELECT 
							".$db->nameQuote("fieldcode").", 
							".$db->nameQuote("id")." 
					FROM 
							".$db->nameQuote("#__community_fields")."
					WHERE 
							".$db->nameQuote("fieldcode")." IN (".$db->Quote($town_field_code).", ".$db->Quote($state_field_code).", ".$db->Quote($country_field_code).")";
							
			$db->setQuery($sql);
			$row = $db->loadObjectList();
			
			return $row;
		}
		
		function getFriends($userid, $limit)
		{
			$db =& JFactory::getDBO();
			
			$query	= 'SELECT ' . $db->nameQuote( 'connect_from' ) . ' AS ids '
					. 'FROM ' . $db->nameQuote( '#__community_connection' ) . ' '
					. 'WHERE ' . $db->nameQuote( 'connect_to' ) . '=' . $db->Quote( $userid ) . ' '
					. 'AND ' . $db->nameQuote( 'status' ) . '=' . $db->Quote( 1 );
			
			if($limit != 0)
			{
				$query .=" LIMIT ".$limit;
			}				

			$db->setQuery($query);
			
			$friends	= $db->loadResultArray();
			
			CFactory::loadUsers( $friends );
			
			$result		= array();
			$my			= CFactory::getUser();
			$model		= CFactory::getModel( 'Friends' );
			$userFriends	= $model->getFriendIds( $userid );

			foreach( $friends as $friendId )
			{
				$user	= CFactory::getUser( $friendId );
				$params	= $user->getParams();
				$privacy	= $params->get( 'privacyProfileView' ); 
				
				if( $my->id == $userid )
				{
					$result[]	= $friendId;
				}
				
				if( $privacy == 0 )
				{
					$result[]	= $friendId;	
				}
				else if( $privacy == 20 && $my->id != 0 )
				{
					$result[]	= $friendId;
				}
				else if( $privacy == 30 && in_array( $my->id , $userFriends ) )
				{
					$result[]	= $friendId;
				}
			}
			return $result;
		}
		
		function getFriendsLocation($friends, $town_field_id, $state_field_id, $country_field_id, $show_karma)
		{
			require_once( JPATH_ROOT . DS . 'components' . DS . 'com_community' . DS . 'libraries' . DS . 'core.php');
			include_once( JPATH_ROOT . DS . 'components'.DS.'com_community'.DS.'libraries'.DS.'userpoints.php');
			
			$db =& JFactory::getDBO();

			$friends_id = "";
			$count = "";
			$total = count($friends) - 1;
			foreach($friends as $friend)
			{
				$friends_id .= $friend;
				if($count < $total)
				{
					$friends_id .= ",";
				}
				$count++;
			}

			$sql = "SELECT 
				      		a.user_id,
				      		a.value AS country,
				      		b.value AS state,
							c.value	AS town								      		
				    FROM
				      		".$db->nameQuote('#__community_fields_values')." AS a 
				    LEFT JOIN 
				       		".$db->nameQuote('#__community_fields_values')." AS b ON a.user_id=b.user_id AND b.field_id = ".$db->Quote($state_field_id)."
				    LEFT JOIN 
				       		".$db->nameQuote('#__community_fields_values')." AS c ON a.user_id=c.user_id AND c.field_id = ".$db->Quote($town_field_id)."   
				    WHERE
				      		a.field_id = ".$db->Quote($country_field_id)." AND
				      		a.user_id IN (".$friends_id.")";
						
			$db->setQuery($sql);
			$row = $db->loadObjectList();
			
			// preload all users
			$CFactoryMethod = get_class_methods('CFactory');					
			if(in_array('loadUsers', $CFactoryMethod))
			{
				$uids = array();
				foreach($row as $m)
				{
					$uids[] = $m->user_id;
				}
				CFactory::loadUsers($uids);
			}
				
			$location = JArrayHelper::toObject($location);
			
			foreach($row as $data){
				$user = CFactory::getUser($data->user_id);
				$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->username = $user->getDisplayName();
				$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->avatar = $user->getThumbAvatar();
				$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->link = CRoute::_('index.php?option=com_community&view=profile&userid='.$data->user_id);
				
				switch($show_karma){
					case 1:
						$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->karma_points = "<div><img src='".CUserPoints::getPointsImage($user)."' alt=''/></div>";
						break;
					case 2:
						$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->karma_points = "<div><small>".JText::_('MOD_TOPMEMBERS POINTS').": ".$user->_points."</small></div>";
						break;
					default :	
						$location->{$data->town.", ".$data->state.", ".$data->country}->{$data->user_id}->karma_points = "<div></div>";			
				}			
			}
			
			return $location;
		}
	 	 	 	 		
		function onProfileDisplay()
		{	
			JPlugin::loadLanguage( 'plg_friendslocation', JPATH_ADMINISTRATOR );
			
			$config	= CFactory::getConfig();
					
			// Attach CSS
			$document	=& JFactory::getDocument();
			$css		= JURI::base() . 'plugins/community/friendslocation/style.css';
			$document->addStyleSheet($css);
			
			$userid	= $this->_user->id;		
			$def_limit = $this->params->get('count', 0);		
			$mapkey = $this->params->get('mapkey', '');
			$width = $this->params->get('width', '480');
			$height = $this->params->get('height', '340');
			$widgetwidth = $this->params->get('widgetwidth', '203');
			$widgetheight = $this->params->get('widgetwidth', '340');
			$auto_zoom = $this->params->get('auto_zoom', '1');
			$auto_center = $this->params->get('auto_center', '1');			
			
			$document->addScript("http://maps.google.com/maps?file=api&amp;v=2&amp;key=".$mapkey);
			
			$show_karma = 0;
			if($config->get('enablekarma'))
			{
				$show_karma = $this->params->get('show_karma', '1');
			}
			
			$mouse_scroll_zoom = $this->params->get('mouse_scroll_zoom', '1');
			$continuous_zoom = $this->params->get('continuous_zoom', '1');
			
			$column = $this->getLocationFieldId($this->params->get("town_field_code", "FIELD_CITY"), $this->params->get("state_field_code", "FIELD_STATE"), $this->params->get("country_field_code", "FIELD_COUNTRY"));
			
			$town_field_id = "";
			$country_field_id = "";
			
			foreach($column as $field){
				switch($field->fieldcode){
					case $this->params->get("town_field_code", "FIELD_CITY"):
						$town_field_id = $field->id;
						break;
					case $this->params->get("country_field_code", "FIELD_COUNTRY"):
						$country_field_id = $field->id;
						break;
					case $this->params->get("state_field_code", "FIELD_STATE"):
						$state_field_id = $field->id;
						break;
					default:
						break;
				}
			}
					
			if(!empty($town_field_id) && !empty($state_field_id) && !empty($country_field_id)){
				
				$mainframe =& JFactory::getApplication();
				$caching = $this->params->get('cache', 1);		
				if($caching)
				{
					$caching = $mainframe->getCfg('caching');
				}
				
				$layout = $this->getLayout();
				
				$cache =& JFactory::getCache('plgCommunityFriendsLocation');
				$cache->setCaching($caching);
				$callback = array('plgCommunityFriendsLocation', '_getFriendsLocationHTML');		
				$content = $cache->call($callback, $mapkey, $width, $height, $widgetwidth, $widgetheight, $auto_zoom, $auto_center, $mouse_scroll_zoom, $continuous_zoom, $show_karma, $town_field_id, $state_field_id, $country_field_id, $userid, $def_limit, $layout);
			}else{
				$content = "<div>".JText::_("PLG_FRIENDSLOCATION FIELD CODE NOT FOUND")."</div>";
			}
			
			return $content;
		}
		
		function ajaxGoogleMap( $response ){
			$response->addScriptCall('runMap();');
			return $response->sendResponse();
		}
		
		function _getFriendsLocationHTML($mapkey, $width, $height, $widgetwidth, $widgetheight, $auto_zoom, $auto_center, $mouse_scroll_zoom, $continuous_zoom, $show_karma, $town_field_id, $state_field_id, $country_field_id, $userid, $def_limit, $layout)
		{
			ob_start();
			if(!empty($mapkey))
			{
				$friends = plgCommunityFriendsLocation::getFriends($userid, $def_limit);						
				if(!empty($friends))
				{
					$friends_location = plgCommunityFriendsLocation::getFriendsLocation($friends, $town_field_id, $state_field_id, $country_field_id, $show_karma);
					$script='
				    	var geocoder = null;
				    	var map = null;
				    	var bounds = null;
				    	var baseIcon = null;				    	
				    	var auto_zoom = "'.$auto_zoom.'";
				    	var auto_center = "'.$auto_center.'";
				    	var mouse_scroll_zoom = "'.$mouse_scroll_zoom.'";
				    	var continuous_zoom = "'.$continuous_zoom.'";
				    	var caught_error = "0";
					';
				    				    	
				    if(!empty($friends_location))
					{
						$script.='var address = {';				    	
						$counter_loc = 0;
						$end_counter_loc = count((array)$friends_location) - 1;
						foreach($friends_location as $loc_key=>$location)
						{
							$script.= '"'.addslashes($loc_key).'":{';
							$counter_friends = 0;
							$end_counter_friends = count((array)$location) - 1;
							foreach($location as $fr_key=>$friends)
							{
								$script.= '"'.addslashes($fr_key).'":{';
								$counter_data = 0;
								$end_counter_data = count((array)$friends) - 1;
								foreach($friends as $data_key=>$value)
								{
									$script.= '"'.addslashes($data_key).'":["'.addslashes($value).'"]';
									if($counter_data < $end_counter_data)
									{
										$script.=',';
									}
									$counter_data++;
								}
								$script.='}';
								if($counter_friends < $end_counter_friends)
								{
									$script.=',';
								}
								$counter_friends++;
							}
							$script.='}';
							if($counter_loc < $end_counter_loc)
							{
								$script.=',';
							}
							$counter_loc++;
						}
						$script.='}';
						
		    		}
					else
					{
						$script .= 'caught_error = "1"';
					}
		    		
					$script .='
					
			            joms.plugins.extend({
							mycontacts: {
								initialize: function(){
									initializeMap();
									jax.call("community", "plugins,friendslocation,ajaxGoogleMap");
								}
							}
						});

											
						function initializeMap()
						{
							map = new GMap2(document.getElementById("map_canvas"));
							map.setCenter(new GLatLng(0, 0), 1);
							map.addControl(new GSmallMapControl());
							map.addControl(new GMapTypeControl());					
							
							if(mouse_scroll_zoom == "1"){
								map.enableScrollWheelZoom();
							}
				    	
							if(continuous_zoom == "1"){
								map.enableContinuousZoom();
							}					
							
							bounds = new GLatLngBounds();
							geocoder = new GClientGeocoder();						
							
							baseIcon = new GIcon(G_DEFAULT_ICON);						
							baseIcon.iconSize = new GSize(20, 34);						
							baseIcon.iconAnchor = new GPoint(9, 34);
							baseIcon.infoWindowAnchor = new GPoint(9, 2);
						}						        
								
						function addAddressToMap(response){	
							if (!response || response.Status.code != 200){
								//alert("Sorry, we were unable to geocode that address");
							}else{
								var total_ppl = 0;
								for (var l in address[response.name]){
									total_ppl++;
								}
								
								var marker_temp = total_ppl + "'.JText::_('PLG_FRIENDSLOCATION FRIEND STAY').'<br />";
								
								for (var j in address[response.name]) {
									marker_temp += "<div style=\'float: left; width: 32px; margin-top: 4px;\'><img src=\'"+address[response.name][j]["avatar"][0]+"\' width=40 height=40 alt=\'\'></div><div style=\'margin-left: 45px; margin-top: 3px;\'><a href=\'"+address[response.name][j]["link"][0]+"\'>"+address[response.name][j]["username"][0]+"</a>"+address[response.name][j]["karma_points"][0]+"<div style=\'clear: both; height: 1px;\'>&nbsp;</div></div>";
								}
																														
								place = response.Placemark[0];
								point = new GLatLng(place.Point.coordinates[1],
								                    place.Point.coordinates[0]);
								
			 					var marker = new GMarker(point);
			 					bounds.extend(point);
			 					GEvent.addListener( marker, "click" , function(){
			 						marker.openInfoWindowHtml( "<B>'.JText::_('PLG_FRIENDSLOCATION LOCATION').'</B> : " + response.Placemark[0].address + "<br /><br />" + marker_temp);
								 } );
								
								map.addOverlay(marker);
								
								if(auto_zoom == "1"){
					 				map.setZoom(map.getBoundsZoomLevel(bounds));
					 			}
					 			
					 			if(auto_center == "1"){
					 				map.setCenter(bounds.getCenter());
					 			}
							}
						}
						
						function runMap(){			
							if(caught_error!="1"){
								if (GBrowserIsCompatible()) {
									for (var i in address){				 			
						 				geocoder.getLocations( i, addAddressToMap);
									}
						 		}
					 		}		
					    }
					    
					    /*
					    joms.jQuery(document).ready( function() {
					    	initialize();
							jax.call("community", "plugins,friendslocation,ajaxGoogleMap");
						});
						*/
						
						joms.jQuery(window).unload( function() {
							GUnload();
						});';
						
					$document	=& JFactory::getDocument();
					$document->addScriptDeclaration($script);
					
					switch($layout)
					{
						case "sidebar-top":
						case "sidebar-bottom":
							$content = plgCommunityFriendsLocation::_widgetLayout($widgetwidth, $widgetheight);
							break;
						case "content":
						default:
							$content = plgCommunityFriendsLocation::_contentLayout($width, $height);
							break;
					}
					
					echo $content;
				}
				else
				{
				    
			?>
            <div id="application-flocations">		
                <div><?php echo JText::_("PLG_FRIENDSLOCATION NO FRIENDS YET")?></div>
            </div>
			<?php
				}
			}
			else
			{
			?>
			<div id="application-flocations">
    			<div class="nopost">
                    <img class="icon-nopost" src='<?php echo JURI::base()."components/com_community/assets/error.gif"; ?>' alt="" />
                    <span class="content-nopost">
                    <?php echo JText::_("PLG_FRIENDSLOCATION NOT CONFIGURED"); ?>
                    </span>
                </div>
            </div>
			<?php		
			}
			$html = ob_get_contents();
			@ob_end_clean();
			
			return $html;
		}
		
		function onAppDisplay()
		{
			ob_start();
			$limit=0;
			$html= $this->onProfileDisplay($limit);
			echo $html;
			
			$content	= ob_get_contents();
			ob_end_clean(); 
		
			return $content;
			
		}
		
		function _widgetLayout($width, $height)
		{
			return '<div id="map_canvas" style="width:'.$width.'px; height:'.$height.'px"></div>';
		}
		
		function _contentLayout($width, $height)
		{
			return '<div id="map_canvas" style="width:'.$width.'px; height:'.$height.'px"></div>';
		}
				
		function getRefreshAction()
		{
			$script = array();
			
			$script[] = 'initialize();';
			$script[] = 'jax.call("community", "plugins,friendslocation,ajaxGoogleMap");';
			
			return $script;
		}
	}	
}